AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua' )

local nextspark = 0
local duration = 0
local sfx = Sound( "Metal.SawbladeStick" )

local function ragdollply(ply)
	local rag = ents.Create( "prop_ragdoll" )

    	if not rag:IsValid() then return end

	rag:SetModel( ply:GetModel() )
    	rag:SetKeyValue( "origin", ply:GetPos().x .. " " .. ply:GetPos().y .. " " .. ply:GetPos().z )
	rag:SetAngles(ply:GetAngles())
	rag:SetColor( 0, 255, 0, 255 )
	rag:SetMaterial("models/debug/debugwhite")
	rag:Ignite( 30, 2 )
			
	rag.ply = ply
	
	ply:StripWeapons()
	ply:DrawViewModel(false)
	ply:DrawWorldModel(false)
	ply:Spectate(OBS_MODE_CHASE)
	ply:SpectateEntity(rag)
	
    	rag:Spawn()
    	rag:Activate()

	rag:GetPhysicsObject():SetVelocity(4*ply:GetVelocity())
	
	return rag
end

local function killconstr( Entity )
	
	local color1 = math.random(0, 255)
	local color2 = math.random(0, 255)
	local color3 = math.random(0, 255)
		
	if (!Entity) then return false end
	if (!Entity:IsValid()) then return false end
	if (Entity:IsPlayer()) then return false end

	if ( CLIENT ) then return true end

	Entity:SetMaterial("models/debug/debugwhite")
	Entity:SetColor(color1, color2, color3, 255)

	constraint.RemoveAll( Entity )
	
	return true
end

function ENT:SpawnFunction(ply, tr)
	if ( !tr.Hit ) then return end
	local SpawnPos = tr.HitPos + tr.HitNormal * 16
	local ent = ents.Create("MingeBlok")
	ent:SetPos(SpawnPos)
	ent:Spawn()
	ent:Activate()
	return ent
end

function ENT:Initialize()
	self.Entity:SetMaterial("models/debug/debugwhite")
	self.Entity:SetColor(0,255,0,255)
	self.Entity:SetGravity( 0.5 )
	self.Entity:SetModel("models/props_junk/cinderblock01a.mdl")
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )
	if (phys:IsValid()) then
		phys:Wake()
	end
end

function ENT:OnTakeDamage(dmg)
	self.Entity:TakePhysicsDamage(dmg)
end

function ENT:Touch(ent)
	
	if (ent:IsValid()) && (!ent:IsPlayer()) then
		
		local Slvs = constraint.GetAllConstrainedEntities( ent )
		local count = 0

		
    if (nextspark <= CurTime()) then
		local fx = EffectData()
			fx:SetOrigin(self.Entity:GetPos())
			fx:SetScale( 1 )
			fx:SetMagnitude( 10 )
			fx:SetRadius( 16 )
		util.Effect( "Sparks", fx )
		self.Entity:EmitSound( sfx )
      		nextspark = CurTime() + 1
    end

		for _, Entity in pairs( Slvs ) do
			ent:GetPhysicsObject():EnableMotion(true)
			ent:GetPhysicsObject():Wake()
			if (killconstr( Entity )) then
				count = count + 1
			end
		end
	end

	if (ent:IsPlayer()) then
		local Blok = self.Entity
		local victem = ent
		
    if (duration <= CurTime()) then
	ragdollply(victem)
	duration = CurTime() + 2
    end


		victem:StripWeapons()

		

		for k, v in pairs(player.GetAll()) do
			v:ChatPrint(victem:Nick().." is gay!")
		end
	end
end